package com.a01_2021.thousandstimes.general.jwt;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author E1xP@foxmail.com
 * @Version 1.0
 * @PACKAGE_NAME com.a01_2021.thousandstimes.auth.jwt
 * @CLASS_NAME JwtAuthenticationTokenFilter
 * @Description TODO JWT令牌过滤器
 * @Date 2021/2/24 下午 4:08
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String jwtToken = httpServletRequest.getHeader(jwtTokenUtil.getHeader());//获取header中的Jtw令牌
        if (!StringUtils.isEmpty(jwtToken)) {
            //获取用户名与实例id
            String username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            String instanceIdToken = jwtTokenUtil.getInstanceIdFromToken(jwtToken);
            if (username != null &&
                    instanceIdToken != null &&
                    SecurityContextHolder.getContext().getAuthentication() == null &&
                    httpServletRequest.getHeader("instanceid").equals(instanceIdToken)) {//校验用户名与实例id
                //未授权用户
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);//获取用户信息与授权情况
                if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                    //令牌未过期,授予权限
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
